<!-- 页面路由配置 -->
<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '换油订单详情',
    navigationStyle: 'custom',
    disableScroll: true, // 微信禁止页面滚动
    'app-plus': {
      bounce: 'none', // 禁用 iOS 弹性效果
    },
  },
}
</route>

<!-- 页面模板 -->
<template>
  <PageLayout navTitle="换油订单详情" backRouteName="exchangeOrder" routeMethod="pushTab">
    <!-- 滚动区域 -->
    <scroll-view class="scrollArea" scroll-y>
      <!-- 表单容器 -->
      <view class="form-container">
        <wd-form ref="form" :model="formData">
          <wd-cell-group border:true>
            <wd-collapse v-model="collapseValue" collapse>
              <wd-collapse-item title="基本信息" name="item1">
                <!-- 单据编号 -->
                <view class="form-item">
                  <wd-cell title="单据编号" :value="formData.orderNo"></wd-cell>
                </view>
                <!-- 订单状态 -->
                <view class="form-item">
                  <wd-cell title="订单状态">
                    <dictItem
                      dict-code="exchange_oil_order_status"
                      :value="formData.status"
                    ></dictItem>
                  </wd-cell>
                </view>
                <!-- 原料类型选择器 -->
                <view class="form-item">
                  <wd-cell title="原料类型">
                    <wd-select-picker
                      type="radio"
                      prop="materialType"
                      v-model="formData.materialType"
                      :columns="materialTypes"
                      :readonly="!isEditable"
                      title="请选择原料类型"
                      :safe-area-inset-bottom="false"
                      :rules="[{ required: isEditable, message: '请选择原料类型' }]"
                    ></wd-select-picker>
                  </wd-cell>
                </view>

                <!-- 客户名称 -->
                <view v-if="formData.farmerName" class="form-item">
                  <wd-cell title="客户名称" :value="formData.farmerName"></wd-cell>
                </view>
                <!-- 联系方式输入框 -->
                <view class="form-item">
                  <wd-input
                    label="联系方式"
                    label-width="75px"
                    prop="mob"
                    v-model="formData.mob"
                    :readonly="!isEditable"
                    :rules="[
                      { required: isEditable, message: '请填写联系方式' },
                      {
                        required: isEditable,
                        pattern: /^\d+$/,
                        message: '只能输入数字，请重新输入',
                      },
                      {
                        required: isEditable,
                        validator: validatePhone,
                        message: '请输入有效的手机号',
                      },
                    ]"
                    placeholder="请输入联系方式"
                    @blur="validatePhone"
                  >
                    <template #extra>
                      <view class="phone-tip" v-if="showPhoneTip">只能输入数字，请重新输入</view>
                    </template>
                    <template #suffix>
                      <button
                        class="custom-phone-button"
                        open-type="getPhoneNumber"
                        @getphonenumber="getPhoneNumber"
                        style="margin-left: 10px"
                        v-if="isEditable"
                      >
                        微信手机
                      </button>
                    </template>
                  </wd-input>
                </view>
                <!-- 位置 -->
                <view class="form-item">
                  <wd-input
                    label="地址"
                    :readonly="!isEditable"
                    label-width="50px"
                    placeholder="请输入或选择地址"
                    v-model="formData.address"
                  >
                    <template #suffix>
                      <button
                        class="custom-phone-button"
                        @click="goToLocationPage"
                        style="margin-left: 10px"
                        v-if="isEditable"
                      >
                        选择地址
                      </button>
                    </template>
                  </wd-input>
                </view>
                <!-- 预估重量输入框 -->
                <view class="form-item">
                  <wd-input
                    :label="`${formData.materialType === 'A' ? '茶籽' : '茶果'}预估重量`"
                    label-width="120px"
                    prop="estimatedWeight"
                    v-model="formData.estimatedWeight"
                    :readonly="!isEditable"
                    placeholder="请输入预估重量"
                    :rules="[
                      { required: isEditable, message: '请填写预估重量' },
                      { required: isEditable, pattern: /^\d+$/, message: '只能输入数字' },
                      {
                        required: isEditable,
                        validator: (value) => value >= 0 && value <= 9999999,
                        message: '范围：0-9999999',
                      },
                    ]"
                    type="number"
                  >
                    <template #suffix>kg</template>
                  </wd-input>
                </view>
                <!-- 备注输入框 -->
                <view class="form-item">
                  <wd-textarea
                    label="备注"
                    label-width="100px"
                    prop="comments"
                    :readonly="!isEditable"
                    v-model="formData.comments"
                    :rules="[
                      { required: isEditable, max: 1000, message: '备注最多只能输入1000个字符' },
                    ]"
                    :maxlength="1000"
                    auto-height
                    placeholder="请输入备注"
                  ></wd-textarea>
                </view>
                <!-- 预估重量输入框 -->
                <view class="form-item" v-if="userRole === 'factory' && formData.status === 'C'">
                  <wd-calendar
                    type="datetime"
                    label="计划到货时间"
                    label-width="120px"
                    prop="exchangeTime.arrivalTime"
                    v-model="formData.exchangeTime.arrivalTime"
                    placeholder="请选择时间"
                    :readonly="formData.status !== 'C'"
                    :rules="[{ required: true, message: '请填计划到货时间' }]"
                  />
                </view>
              </wd-collapse-item>
              <wd-collapse-item
                title="工厂关键参数"
                v-if="!['A', 'B', 'C'].includes(formData.status)"
                name="item2"
              >
                <!-- 工厂名称 -->
                <view v-if="formData.factoryName" class="form-item">
                  <wd-cell title="工厂名称">{{ formData.factoryName }}</wd-cell>
                </view>
                <!-- 进场重量 -->
                <view v-if="formData.grossWeight" class="form-item">
                  <wd-cell title="进场重量">{{ formData.grossWeight }} kg</wd-cell>
                </view>
                <!-- 含油率 -->
                <view v-if="formData.oilYield && formData.qualityOilYield" class="form-item">
                  <wd-cell title="含油率">{{ formData.qualityOilYield }} %</wd-cell>
                </view>
                <!-- 皮重 -->
                <view
                  v-if="formData.rawStockin && formData.rawStockin.stockinTareWeight"
                  class="form-item"
                >
                  <wd-cell title="皮重">{{ formData.rawStockin.stockinTareWeight }} kg</wd-cell>
                </view>
                <!-- 净重 -->
                <view
                  v-if="formData.rawStockin && formData.rawStockin.stockinNetWeight"
                  class="form-item"
                >
                  <wd-cell title="净重">{{ formData.rawStockin.stockinNetWeight }} kg</wd-cell>
                </view>

                <!-- 茶饼补油 -->
                <view
                  v-if="
                    formData.oilYield &&
                    (userRoleId === 'fac_produce_emp' || formData.oilYield.teaCakeAdd) &&
                    formData.status === 'K'
                  "
                  class="form-item"
                >
                  <wd-input
                    v-if="userRoleId === 'fac_produce_emp'"
                    label="茶饼补油"
                    v-model="formData.oilYield.teaCakeAdd"
                    type="number"
                    :readonly="userRoleId !== 'fac_produce_emp'"
                    :min="0"
                  >
                    <template #suffix>kg</template>
                  </wd-input>
                  <wd-cell
                    v-else
                    title="茶饼补油"
                    :value="formData.oilYield.teaCakeAdd + ' kg'"
                  ></wd-cell>
                </view>

                <view
                  v-if="formData.oilYield && formData.oilYield.teaSeedYieldOfCake"
                  class="form-item"
                >
                  <wd-cell title="得油量">
                    {{
                      formData.oilYield.teaCakeAdd
                        ? Number(formData.oilYield.teaSeedYieldOfCake).toFixed(2)
                        : (
                            Number(formData.oilYield.teaCakeAdd || 0) +
                            Number(formData.oilYield.teaSeedYieldOfCake || 0)
                          ).toFixed(2)
                    }}
                    kg
                  </wd-cell>
                </view>
                <!-- 付款金额 -->
                <view v-if="formData.paymentAmount" class="form-item">
                  <wd-cell title="付款金额">{{ formData.paymentAmount }} 元</wd-cell>
                </view>
              </wd-collapse-item>
              <wd-collapse-item
                title="质检单"
                name="item3"
                v-if="
                  userRole !== 'grows' &&
                  isShowItem(['F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']) &&
                  formData.quality &&
                  formData.quality[0] != null
                "
              >
                <view
                  class="quality-item"
                  v-for="(quality, index) in formData.quality"
                  key="quality.qualityNo"
                >
                  <wd-card>
                    <template #title>
                      <view class="quality-title">
                        <view style="color: red">
                          {{ '单据' + (index + 1) + ': ' + quality.qualityNo }}
                        </view>
                        <view class="quality-btns">
                          <!-- <wd-button
                            class="hold-form"
                            size="small"
                            block
                            @click="updateQuality(quality)"
                            v-if="shouldShowButton('修改质检单')"
                          >
                            修改质检单
                          </wd-button> -->
                          <wd-button
                            type="text"
                            icon="delete"
                            size="small"
                            block
                            @click="deleteQuality(quality)"
                            v-if="
                              userRoleId === 'fac_qulity_control_emp' &&
                              hasPermission('app:exchange_order:delete_quality') &&
                              shouldShowButton('删除此质检单')
                            "
                          >
                            删除此质检单
                          </wd-button>
                        </view>
                      </view>
                    </template>
                    <!-- 品控人员 -->
                    <view class="form-item">
                      <wd-cell title="品控人员" v-if="quality.feIdName">
                        {{ quality.feIdName }}
                      </wd-cell>
                    </view>
                    <!-- 检测时间 -->
                    <view class="form-item">
                      <wd-cell title="检测时间" v-if="quality.createTime">
                        {{ quality.createTime }}
                      </wd-cell>
                    </view>
                    <!-- 外观 -->
                    <view class="form-item">
                      <wd-cell title="外观" v-if="quality.qualityLook">
                        {{ quality.qualityLook }}
                      </wd-cell>
                    </view>

                    <!-- 酸价 -->
                    <view class="form-item">
                      <wd-cell title="酸价" v-if="quality.qualityAcid">
                        {{ quality.qualityAcid }}mg/g
                      </wd-cell>
                    </view>
                    <!-- 气味 -->
                    <view class="form-item">
                      <wd-cell title="气味" v-if="quality.qualitySmell">
                        {{ quality.qualitySmell }}
                      </wd-cell>
                    </view>
                    <!-- 水分 -->
                    <view class="form-item">
                      <wd-cell title="水分" v-if="quality.qualityWater">
                        {{ quality.qualityWater }}%
                      </wd-cell>
                    </view>
                    <!-- 不完善率(含虫吃率、未成熟率、霉变率) -->
                    <view class="form-item" v-if="quality.qualityImperfectionRate">
                      <wd-cell title="不完善率(含虫吃率、未成熟率、霉变率)" title-width="230px">
                        {{ quality.qualityImperfectionRate }}%
                      </wd-cell>
                    </view>
                    <!-- 杂质 -->
                    <view class="form-item" v-if="quality.qualityDirt">
                      <wd-cell title="杂质">{{ quality.qualityDirt }}%</wd-cell>
                    </view>
                    <!-- 含油率 -->
                    <view class="form-item" v-if="quality.qualityOilYield">
                      <wd-cell title="含油率">{{ quality.qualityOilYield }}%</wd-cell>
                    </view>
                    <!-- 出干籽率 -->
                    <view class="form-item" v-if="quality.qualitySeedRate">
                      <wd-cell title="出干籽率">{{ quality.qualitySeedRate }}%</wd-cell>
                    </view>
                    <!-- 质检结果 -->
                    <view
                      class="form-item"
                      v-if="quality.qualityResult !== null && quality.qualityResult !== ''"
                    >
                      <wd-cell title="质检结果">
                        {{ quality.qualityResult === '0' ? '合格' : '不合格' }}
                      </wd-cell>
                    </view>
                    <view
                      class="form-item qulity-btns"
                      v-if="
                        quality.isConfirm === '2' && userRoleId === 'fac_qulity_control_manager'
                      "
                    >
                      <view
                        class="qulity-confirmation"
                        @click="confirmQuality('确认质检合格', '1', quality)"
                        v-if="hasPermission('app:exchange_order:onfirmation_quality_qualified')"
                      >
                        确认质检合格
                      </view>
                      <view
                        class="qulity-returned"
                        @click="confirmQuality('返回重新质检', '2', quality)"
                        v-if="hasPermission('app:exchange_order:returned_re_inspect') && index < 2"
                      >
                        返回重新质检
                      </view>
                      <view
                        class="qulity-unqualified"
                        @click="confirmQuality('不合格退货', '3', quality)"
                        v-if="hasPermission('app:exchange_order:unqualified_return')"
                      >
                        不合格退货
                      </view>
                    </view>
                    <view class="form-item" v-else>
                      <wd-cell title="品控经理审核状态">
                        <view v-if="quality.isConfirm === '0'" class="confirmStatus0">
                          确认质检合格
                        </view>
                        <view v-if="quality.isConfirm === '1'" class="confirmStatus1">
                          返回重新质检
                        </view>
                        <view v-if="quality.isConfirm === '2'" class="confirmStatus2">未审核</view>
                        <view v-if="quality.isConfirm === '3'" class="confirmStatus3">
                          不合格退货
                        </view>
                      </wd-cell>
                    </view>
                  </wd-card>
                </view>
              </wd-collapse-item>
              <wd-collapse-item title="订单履历" name="item4" v-if="formData.status !== 'A'">
                <view class="order-history">
                  <wd-cell
                    v-for="(item, index) in formData.operationLogs"
                    :title="item.operationNode"
                    :key="index"
                  >
                    {{ item.createTime }}
                  </wd-cell>
                </view>
              </wd-collapse-item>
            </wd-collapse>
            <!-- 已阅读并同意《换油须知》选项 -->
            <!-- <view class="agreement-container">
                <wd-checkbox
                  v-model="formData.agreedToTerms"
                  prop="agreedToTerms"
                  :rules="[{ validator: (value) => value === '111', message: '请选中已阅读并同意' }]"
                >
                  已阅读并同意
                </wd-checkbox>
                <wd-text
                  type="primary"
                  class="agreement-link"
                  @click="openTermsDocument"
                  text="《换油须知》"
                ></wd-text>
              </view> -->
          </wd-cell-group>
        </wd-form>
      </view>
      <view class="konw-and-agree">
        <wd-checkbox
          v-if="isEditable"
          checked-color="#01b43f"
          v-model="formData.agreedToTerms"
          @change="handleknow"
        >
          已阅读并同意换油须知
        </wd-checkbox>
      </view>
    </scroll-view>

    <!-- 底部按钮区域 -->
    <view class="footer">
      <!-- 种植户按钮区域 -->
      <wd-button
        block
        type="info"
        @click="handleStaging"
        v-if="hasPermission('app:exchange_order:temporary_storage') && shouldShowButton('暂存')"
      >
        暂存
      </wd-button>
      <wd-button
        class="hold-form"
        block
        type="success"
        @click="deleteOrder"
        v-if="hasPermission('app:exchange_order:order_delete') && shouldShowButton('删除')"
      >
        删除
      </wd-button>
      <wd-button
        class="submit-form"
        block
        @click="handleSubmit"
        v-if="hasPermission('app:exchange_order:order_submit') && shouldShowButton('提交')"
      >
        提交
      </wd-button>
      <wd-button
        class="hold-form"
        block
        type="success"
        @click="cancelOrder"
        v-if="hasPermission('app:exchange_order:cancel_order') && shouldShowButton('取消订单')"
      >
        取消订单
      </wd-button>
      <!-- 生产确认得油 -->
      <wd-button
        class="submit-form"
        block
        @click="confirmOil('1')"
        v-if="showProduceConfirm && hasPermission('app:exchange_order:factory_oil_confirmation')"
      >
        确认得油
      </wd-button>
      <!-- 财务确认得油 -->
      <wd-button
        class="submit-form"
        block
        @click="confirmOil('1')"
        v-if="showFinanceConfirm && hasPermission('app:exchange_order:finance_oil_confirmation')"
      >
        确认得油
      </wd-button>
      <!-- 种植户确认得油 -->
      <wd-button
        class="submit-form"
        block
        @click="confirmOil('1')"
        v-if="showGrowerConfirm && hasPermission('app:exchange_order:grows_oil_confirmation')"
      >
        得油结果确认
      </wd-button>

      <wd-button
        class="hold-form"
        block
        @click="confirmOil('2')"
        v-if="showGrowerConfirm && hasPermission('app:exchange_order:grows_oil_veto')"
      >
        不认可得油结果
      </wd-button>
      <!-- <wd-button
        class="submit-form"
        block
        @click="confirmOil('1')"
        v-if="
          hasPermission('app:exchange_order:grows_oil_confirmation') &&
          userRole === 'grows' &&
          formData.financeConfirm === 'Y' &&
          formData.produceConfirm === 'Y' &&
          shouldShowButton('得油结果确认')
        "
      >
        得油结果确认
      </wd-button>
      <wd-button
        class="hold-form"
        block
        @click="confirmOil('2')"
        v-if="
          hasPermission('app:exchange_order:grows_oil_veto') &&
          userRole === 'grows' &&
          formData.financeConfirm === 'Y' &&
          formData.produceConfirm === 'Y' &&
          shouldShowButton('不认可得油结果')
        "
      >
        不认可得油结果
      </wd-button> -->
      <wd-button
        class="submit-form"
        block
        @click="paymentSelect"
        v-if="hasPermission('app:exchange_order:payment') && shouldShowButton('付款')"
      >
        付款
      </wd-button>
      <!-- 工厂用户按钮区域 -->
      <wd-button
        class="hold-form"
        block
        v-if="hasPermission('app:exchange_order:agree') && shouldShowButton('同意')"
        @click="acceptOrRefuse('E')"
      >
        同意
      </wd-button>
      <wd-button
        block
        type="info"
        v-if="hasPermission('app:exchange_order:refuse') && shouldShowButton('拒绝')"
        @click="acceptOrRefuse('D')"
      >
        拒绝
      </wd-button>

      <wd-button
        class="hold-form"
        block
        @click="confirmArrival"
        v-if="hasPermission('app:exchange_order:confirm_receipt') && shouldShowButton('确认到货')"
      >
        确认到货
      </wd-button>
      <wd-button
        class="submit-form"
        block
        @click="fillNetWeightConfirm"
        v-if="
          hasPermission('app:exchange_order:supplement_inventory_data') &&
          shouldShowButton('补录入库数据')
        "
      >
        补录入库数据
      </wd-button>
      <wd-button
        class="hold-form"
        block
        @click="addQuality"
        v-if="hasPermission('app:exchange_order:add_quality') && shouldShowButton('新增质检单')"
      >
        新增质检单
      </wd-button>

      <!-- <wd-button class="hold-form" block v-if="shouldShowButton('质检不认可')">
          质检不认可
        </wd-button>
        <wd-button class="hold-form" block v-if="shouldShowButton('已线下确认')">
          已线下确认
        </wd-button> -->
      <!-- <wd-button class="hold-form" block v-if="shouldShowButton('要求取消')">要求取消</wd-button> -->
      <!-- <wd-button
        class="hold-form"
        block
        @click="confirmOil('1')"
        v-if="
          hasPermission('app:exchange_order:factory_oil_confirmation') &&
          userRole === 'factory' &&
          shouldShowButton('确认得油')
        "
      >
        确认得油
      </wd-button> -->
    </view>
    <QualityEdit ref="qualityEditRef" @confirm="handleQualityEditConfirm" />
    <PaymentSelect ref="paymentSelectRef" @select="handlePaymentSelect" />
    <UploadPayProof ref="uploadPayProofRef" @upload="handleUploadPayProof" />
    <wd-message-box selector="wd-message-box-slot">
      <wd-input label="皮重" v-model="arrivalWeight" type="number" @input="updateNetWeight">
        <template #suffix>kg</template>
      </wd-input>
      <wd-input label="净重" v-model="netWeight" type="number" @input="updateArrivalWeight">
        <template #suffix>kg</template>
      </wd-input>
    </wd-message-box>
    <wd-message-box selector="wd-message-box-slot2">
      <wd-input
        label="进场重量"
        v-model="grossWeight"
        placeholder="请输入进场重量"
        type="number"
        clearable
      >
        <template #suffix>kg</template>
      </wd-input>
    </wd-message-box>
    <wd-popup v-model="show" root-portal position="center" custom-style="height: 200px;">
      <text class="custom-txt">我被传送到了根节点中</text>
    </wd-popup>
  </PageLayout>
</template>

<!-- 脚本部分 -->
<script lang="ts" setup>
import { useToast, useMessage, useNotify } from 'wot-design-uni'
import { useRouter } from '@/plugin/uni-mini-router'
import { useUserStore } from '@/store/user'
import { http } from '@/utils/http'
import { orderApi, userApi, payApi } from '@/api/api'
import { getFileAccessHttpUrl } from '@/common/uitls'
import { ref, reactive } from 'vue'
import { useLocationStore } from '@/store/location'
import { materialTypes, orderStatus } from '@/common/constants'
import { template } from 'lodash-es'
import dayjs from 'dayjs'
import { usePermission } from '@/hooks/usePermission'
import QualityEdit from './components/qualityEdit.vue'
import PaymentSelect from './components/paymentSelect.vue'
import UploadPayProof from './components/uploadPayProof.vue'
import { debounce } from 'lodash'
import dictItem from '@/components/dictItem/dictItem.vue'

const message = useMessage()
const messageWeight = useMessage('wd-message-box-slot')
const messageGrossWeight = useMessage('wd-message-box-slot2')
const { hasPermission } = usePermission()

// 组件选项配置
defineOptions({
  name: 'ExchangeCreateOrder',
  options: {
    styleIsolation: 'shared',
  },
})

// 初始化工具和状态
const toast = useToast()
const router = useRouter()
const userStore = useUserStore()
const locationStore = useLocationStore()
const value = ref<boolean>(true)
const orderId = ref<string>('')
const collapseValue = ref<string[]>(['item1', 'item2', 'item3', 'item4'])

const userRole = ref('') // 'factory' 或 'grower'
const qualityEditRef = ref(null)
const paymentSelectRef = ref(null)
const uploadPayProofRef = ref(null)

const netWeight = ref('') // 皮重
const arrivalWeight = ref('') // 净重
const grossWeight = ref('') // 进场重量

const show = ref(false) // 弹窗显示控制

// 计算属性：判断是否可编辑
const isEditable = computed(() => formData.status === 'A')

const userRoleId = userStore.userInfo.userRole
const userRoleName = userStore.userInfo.userRoleName
if (userRoleName && (userRoleName.includes('工厂') || userRoleName.includes('管理员'))) {
  userRole.value = 'factory'
} else {
  userRole.value = 'grows'
}
// 监听路由参数
onMounted(() => {
  orderId.value = router.route.value.params.orderId as string
  if (orderId.value) fetchOrderInfo()
})

// 表单数据
const formData = reactive({
  materialType: '',
  estimatedWeight: '',
  mob: '',
  address: '',
  status: '',
  comments: '',
  agreedToTerms: false, // 是否同意《换油须知》
  farmerName: '',
  arrivalWeight: '',
  grossWeight: '',
  exchangeTime: {
    arrivalTime: '',
  },
  rawStockin: {
    stockinNetWeight: '',
  },
  oilYield: {
    teaCakeAdd: '',
    oilYield: '',
  },
  quality: [],
  gotOilWeight: '',
  paymentAmount: '',
  operationLogs: [],
})

// 质检结果
const qualityData = reactive({})

// 表单引用
const form = ref(null)

// 初始化时从store加载地址
if (locationStore.selectedLocation) {
  formData.address = locationStore.selectedLocation.address
}
// 监听位置变化
const unsubscribe = locationStore.$subscribe((mutation, state) => {
  if (state.selectedLocation) {
    formData.address = state.selectedLocation.address
  }
})

/**
 * 根据传入的状态判断是否显示某个模块
 * @param statusList
 */
const isShowItem = (statusList) => {
  return statusList.includes(formData.status)
}

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    // debugger
    const res = await http.post(orderApi.getOrderDetail, { id: orderId.value })
    Object.assign(formData, res.result)
    if (!formData.exchangeTime) {
      formData.exchangeTime = { arrivalTime: '' }
    }
    if (!formData.oilYield) {
      formData.oilYield = {
        teaCakeAdd: '',
        oilYield: '',
      }
    }
  } catch (error) {
    toast.error('获取订单信息失败')
  }
}

// 提交表单处理
const handleSubmit = debounce(
  async () => {
    uni.showModal({
      title: '确认',
      content: '确认提交订单？',
      success: async function (res) {
        if (res.confirm) {
          form.value
            .validate()
            .then(async ({ valid, errors }) => {
              if (valid) {
                if (formData.agreedToTerms !== true) {
                  toast.error('请阅读并同意《换油须知》')
                  return
                }
                console.log('表单校验通过，提交数据:', formData)
                const res = await http.post(orderApi.exchangeUpdateOrder, {
                  ...formData,
                  status: 'B',
                })
                if (res.success) {
                  toast.success('保存成功')
                  handleSuccess()
                } else {
                  toast.error(res?.message || '表单保存失败！')
                }
              }
            })
            .catch((error) => {
              console.error('表单校验失败:', error)
              uni.showToast({
                title: '请检查表单内容',
                icon: 'none',
              })
            })
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 暂存表单处理
const handleStaging = debounce(
  async () => {
    const res = await http.post(orderApi.exchangeUpdateOrder, { ...formData, status: 'A' })
    if (res.success) {
      toast.success('暂存成功')
      fetchOrderInfo()
    } else {
      toast.error(res?.message || '暂存失败！')
    }
  },
  2000,
  { leading: true, trailing: false },
)

// 取消订单
const cancelOrder = debounce(
  async () => {
    uni.showModal({
      title: '取消',
      content: '确认取消订单？',
      success: async function (res) {
        if (res.confirm) {
          const res = await http.post(orderApi.cancelOrder, { id: orderId.value })
          if (res.success) {
            toast.success('取消成功')
            fetchOrderInfo()
          } else {
            toast.error(res?.message || '取消失败！')
          }
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 手机号验证状态
const showPhoneTip = ref(false)

// 手机号验证方法
const validatePhone = (value) => {
  showPhoneTip.value = !/^\d+$/.test(value)
  return /^1[3-9]\d{9}$/.test(value)
}

// 打开《换油须知》文档
const openTermsDocument = () => {
  // 这里替换为实际文档的路径或链接
  uni.navigateTo({
    url: '/pages/documents/TermsOfService',
  })
  formData.agreedToTerms = true
}

// 获取微信手机号方法
const getPhoneNumber = async (e: any) => {
  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      throw new Error('用户拒绝了授权')
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 将获取到的手机号填入表单
      formData.mob = res.result as string
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif
    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信环境')
    formData.mob = '13272408547'
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '获取手机号失败')
  }
}

// 跳转到地图选择页面
const goToLocationPage = () => {
  if (locationStore.selectedLocation) {
    locationStore.setTempLocation(locationStore.selectedLocation)
  }

  uni.navigateTo({
    url: '/pages-user/location/location',
  })
}

// 同意协议
const handleknow = (e) => {
  value.value = e.value
}

const handleSuccess = () => {
  setTimeout(() => {
    uni.$emit('refreshList')
    router.back()
  }, 1000)
}

// 删除订单
const deleteOrder = debounce(
  async () => {
    uni.showModal({
      title: '删除',
      content: '确认删除订单？',
      success: async function (res) {
        if (res.confirm) {
          try {
            const res = await http.post(orderApi.deleteOrder, { id: orderId.value })
            if (res.success) {
              toast.success('删除成功')
              handleSuccess()
            } else {
              toast.error(res?.message || '删除失败！')
            }
          } catch (error) {
            toast.error('删除失败')
          }
          // 在这里执行删除操作
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 根据订单状态判断按钮是否需要显示
const shouldShowButton = (buttonName: string): boolean => {
  const status = formData.status
  // console.log(status, userRole.value)
  if (userRole.value === 'grows') {
    switch (status) {
      case 'A': // 待提交
        return ['暂存', '提交', '删除'].includes(buttonName)
      case 'B': // 待分配工厂
        return ['取消订单'].includes(buttonName)
      // case 'I': // 待确认质检
      //   return ['确认质检合格', '不合格退货'].includes(buttonName)
      case 'K': // 待确认得油结果
        return ['得油结果确认', '不认可得油结果'].includes(buttonName)
      case 'M': // 待付款
        return buttonName === '付款'
      default:
        return false
    }
  } else if (userRole.value === 'factory') {
    switch (status) {
      case 'C': // 待接单
        return ['同意', '拒绝'].includes(buttonName)
      case 'E': // 运输中
        return ['确认到货'].includes(buttonName)
      case 'H': // 待入库
        return ['补录入库数据'].includes(buttonName)
      case 'F': // 待质检
        return ['新增质检单', '修改质检单'].includes(buttonName)
      case 'I': // 待确认质检
        return ['删除此质检单', '确认质检合格', '不合格退货'].includes(buttonName)
      // case 'H': // 待入库
      //   return ['质检不认可', '已线下确认', '要求取消'].includes(buttonName)
      // case 'I': // 待确认质检
      //   return ['确认质检合格', '不合格退货'].includes(buttonName)
      case 'K':
        return buttonName === '确认得油'
      default:
        return false
    }
  } else {
    return false
  }
}

// 确认质检结果
const confirmQuality = async (name, type, quality) => {
  uni.showModal({
    title: name,
    content: '确认该质检结果？',
    success: async function (res) {
      if (res.confirm) {
        const qualityId = quality.id
        const res = await http.post(orderApi.confirmQuality, {
          id: orderId.value,
          confirmQualityStatus: type,
          qualityId,
        })
        if (res.success) {
          toast.success('操作成功')
          handleSuccess()
        } else {
          toast.error(res?.message || '操作失败！')
        }
      }
    },
  })
}

// 接受或拒绝订单
const acceptOrRefuse = async (type: 'E' | 'D') => {
  if (type === 'E' && formData.exchangeTime.arrivalTime === '') {
    toast.error('请选择计划到货时间')
    // 触发计划到货时间的校验
    form.value.validate()
    return
  }
  uni.showModal({
    title: '确认' + (type === 'E' ? '接受' : '拒绝'),
    content: '确认' + (type === 'E' ? '接受' : '拒绝') + '订单？',
    success: async function (res) {
      if (res.confirm) {
        const res = await http.post(orderApi.acceptOrRefuse, {
          id: orderId.value,
          status: type,
          planTime: dayjs(formData.exchangeTime.arrivalTime).format('YYYY-MM-DD HH:mm:ss'),
        })
        if (res.success) {
          toast.success('操作成功')
          handleSuccess()
        } else {
          toast.error(res?.message || '操作失败！')
        }
      }
    },
  })
}

// 确认到货
const confirmArrival = async () => {
  messageGrossWeight
    .confirm({
      title: '进场重量',
      confirmButtonText: '确认到货',
    })
    .then(async () => {
      const arrivalWeight = grossWeight.value
      if (arrivalWeight === '') {
        toast.error('请输入进场重量')
        return
      }
      const res = await http.post(orderApi.confirmArrival, { id: orderId.value, arrivalWeight })

      if (res.success) {
        toast.success('确认到货成功')
        handleSuccess()
      } else {
        toast.error(res?.message || '确认到货失败！')
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 新增质检单
const addQuality = () => {
  console.log(formData)
  qualityEditRef.value.open({}, true, formData.materialType)
}

// 编辑质检单
// const updateQuality = (qualityData) => {
//   qualityEditRef.value.open(qualityData, true, formData.materialType)
// }

// 删除质检单
const deleteQuality = async (qualityData) => {
  uni.showModal({
    title: '删除',
    content: '确认删除质检单？',
    success: async function (res) {
      if (res.confirm) {
        // debugger
        const res = await http.post(orderApi.deleteQuality, {
          id: qualityData.id,
          orderId: orderId.value,
        })
        if (res.success) {
          toast.success('删除质检单成功')
          fetchOrderInfo()
        } else {
          toast.error(res?.message || '删除质检单失败！')
        }
      }
    },
  })
}

// 质检单编辑确认回调
const handleQualityEditConfirm = async (qualityData) => {
  console.log('handleQualityEditConfirm', qualityData)
  if (qualityData.id) {
    const res = await http.post(orderApi.updateQuality, {
      ...qualityData,
      orderId: orderId.value,
    })
    if (res.success) {
      toast.success('修改质检单成功')
      fetchOrderInfo()
    } else {
      toast.error(res?.message || '修改质检单失败！')
    }
  } else {
    const res = await http.post(orderApi.addQuality, {
      ...qualityData,
      orderId: orderId.value,
    })
    if (res.success) {
      toast.success('新增质检单成功')
      fetchOrderInfo()
    } else {
      toast.error(res?.message || '新增质检单失败！')
    }
  }
}

// 确认得油结果
const confirmOil = debounce(
  async (type) => {
    uni.showModal({
      title: '确认得油结果',
      content: '确认该得油结果？',
      success: async function (res) {
        if (res.confirm) {
          const res = await http.post(orderApi.confirmOil, {
            id: orderId.value,
            confirmOilYieldStatus: type,
            teaCakeAdd: formData.oilYield.teaCakeAdd,
          })
          if (res.success) {
            toast.success('确认得油成功')
            handleSuccess()
          } else {
            toast.error(res?.message || '操作失败！')
          }
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 补录入库数据
const fillNetWeightConfirm = async () => {
  messageWeight
    .confirm({
      title: '补录入库数据',
      confirmButtonText: '确认入库',
    })
    .then(async () => {
      fillNetWeight()
    })
    .catch((error) => {
      console.log(error)
    })
}

const fillNetWeight = debounce(
  async () => {
    const res = await http.post(orderApi.fillNetWeight, {
      id: orderId.value,
      netWeight: netWeight.value, // 确保使用 .value 获取实际值
      arrivalWeight: String(Number(arrivalWeight.value) + Number(netWeight.value)),
    })
    if (res.success) {
      toast.success('操作成功')
      handleSuccess()
    } else {
      toast.error(res?.message || '操作失败！')
    }
  },
  2000,
  { leading: true, trailing: false },
)

// 选择付款方式
const paymentSelect = () => {
  paymentSelectRef.value.open()
}

// 选择付款方式
const handlePaymentSelect = (type) => {
  console.log('type', type)
  if (type === 'wechat') {
    weixinPay()
  } else {
    uploadPayProofRef.value.open()
  }
}

async function weixinPay() {
  const res = await http.post(payApi.exchangeOrderPay, {
    orderId: orderId.value,
  })
  console.log('当前获得到的prepayid', res.result)
  const orderData = res.result
  // 订单对象，从服务器获取
  wx.requestPayment({
    timeStamp: orderData.timeStamp, // 时间戳字符串
    nonceStr: orderData.nonceStr, // 随机字符串
    package: orderData.packageValue, // 格式为 "prepay_id=xxx"
    signType: orderData.signType, // 签名算法类型
    paySign: orderData.paySign, // 签名值
    success: function (res) {
      getPayStatus(orderId.value)
    },
    fail: function (err) {
      /* 支付失败 */
      console.log(err)
    },
  })
}

async function getPayStatus(orderId) {
  const res = await http.post(payApi.getPayStatus, {
    orderId: orderId,
  })
  if (res.success) {
    console.log('当前获得到的支付状态', res.result)
    if (res.result === 'Y') {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000,
      })
      fetchOrderInfo()
    } else {
      toast.error('支付失败')
    }
  }
}

async function handleUploadPayProof(imageUrl) {
  const res = await http.post(payApi.uploadExchangeOrderPayProof, {
    orderId: orderId.value,
    paymentProofImage: imageUrl,
  })
  if (res.success) {
    uni.showToast({
      title: '上传支付凭证成功',
      icon: 'success',
      duration: 2000,
    })
    fetchOrderInfo()
  } else {
    toast.error(res?.message || '上传支付凭证失败！')
  }
}

// 输入皮重，净重自动计算=进场重量-皮重
const updateArrivalWeight = async () => {
  const newArrivalWeight = Number(formData.grossWeight) - Number(netWeight.value)
  arrivalWeight.value = newArrivalWeight + ''
}
// 输入净重，皮重自动计算=进场重量-净重
const updateNetWeight = async () => {
  const newTareWeight = Number(formData.grossWeight) - Number(arrivalWeight.value)
  netWeight.value = newTareWeight + ''
}

onUnmounted(() => {
  unsubscribe()
})

// 判断生产人员是否应显示“确认得油”按钮
const showProduceConfirm = computed(() => {
  return (
    userRole.value === 'factory' &&
    userRoleId === 'fac_produce_emp' &&
    formData.status === 'K' &&
    !formData.produceConfirm
  )
})

// 判断财务人员是否应显示“确认得油”按钮
const showFinanceConfirm = computed(() => {
  return (
    userRole.value === 'factory' &&
    userRoleId === 'fac_finance_emp' &&
    formData.status === 'K' &&
    formData.produceConfirm === 'Y' &&
    !formData.financeConfirm
  )
})

// 判断种植户是否应显示“得油结果确认”按钮
const showGrowerConfirm = computed(() => {
  return (
    userRole.value === 'grows' &&
    formData.status === 'K' &&
    formData.produceConfirm === 'Y' &&
    formData.financeConfirm === 'Y'
  )
})
</script>
<style lang="scss" scoped>
@import '@/style/custom/variables.scss';
.footer {
  padding: 10px 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 5px;
  :deep(.wd-button) {
    flex: 1;
  }
}
/* 添加获取手机号按钮样式 */
.custom-phone-button {
  // margin-left: 10px;
  // background: transparent; /* 透明背景 */
  display: inline-flex;
  padding: 0 8px; /* 内边距 */
  height: 28px; /* 高度匹配 wd-button */
  line-height: 28px;
  font-size: 12px; /* 字体大小 */
  color: #333; /* 文字颜色 */
  // border: 1px solid #ddd; /* 边框 */
  // border-radius: 4px; /* 圆角 */
}

/* 如果需要 hover 效果 */
.custom-phone-button:hover {
  opacity: 0.8;
}

// 统一样式
.form-container {
  background: none;
  padding: var(--wot-card-padding, 0 var(--wot-size-side-padding, 15px));
  :deep(.wd-cell__wrapper) {
    padding: 5px 0;
    border-bottom: 1px solid #bbbbbb;
  }

  :deep(.wd-select-picker__cell) {
    padding: 0;
  }
  :deep(.wd-collapse-item__body) {
    background: #f3f3f3;
    border-radius: 16px;
  }
  .form-item {
    // margin: 30upx 20upx;
    // box-shadow: 0 2upx 20upx #000;
    // border-radius: 20upx;
    // border: 4upx solid $primary-color; // 使用 SCSS 变量
    overflow: hidden;
    :deep(.wd-input),
    :deep(.wd-textarea),
    :deep(.wd-textarea__value) {
      background: none;
    }
    :deep(.wd-cell) {
      background: none;
    }
    :deep(.wd-input) {
      margin: 5px 0 5px var(--wot-input-padding, var(--wot-size-side-padding, 15px));
      padding: 0;
      border-bottom: 1px solid #bbbbbb;
    }

    :deep(.wd-select-picker__cell) {
      background: none;
    }
    :deep(.wd-input__body) {
      text-align: right;
    }
    :deep(.wd-select-picker__body) {
      text-align: right;
    }
    :deep(.wd-textarea__value) {
      text-align: right;
    }
  }
}
:deep(.wd-cell-group__body) {
  background: none;
}
:deep(.wd-textarea) {
  // margin: 30upx 20upx;
  border-radius: 30upx;
  // background: none;
}

.footer {
  margin-bottom: 50upx;
}

.footer:deep(.wd-button) {
  border-radius: 40upx !important;
}
.submit-form {
  background: $primary-color !important; // 使用 SCSS 变量
}
.hold-form {
  background: #333333 !important;
}

.konw-and-agree {
  display: flex;
  align-items: center;
  justify-content: center;
  // color: $primary-color; // 使用 SCSS 变量
  :deep(.wd-checkbox__txt) {
    color: $primary-color; // 使用 SCSS 变量
  }
}

.quality-item {
  :deep(.wd-card) {
    margin: 0;
    padding: 0;
  }
  .form-item {
    padding-right: 10px;
  }
  .quality-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .quality-btns {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 5px;
    }
  }
  .form-item {
    :deep(.wd-cell__title) {
      font-size: 12px;
    }
    :deep(.wd-cell__body) {
      font-size: 12px;
    }
  }
  .confirmStatus0 {
    border-radius: 4px;
    background: #1ea262;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus1 {
    border-radius: 4px;
    background: #f20b0b;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus2 {
    border-radius: 4px;
    background: #1373e4;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus3 {
    border-radius: 4px;
    background: #fdd143;
    color: #d54213;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 5px;
  }
  .qulity-confirmation {
    border-radius: 4px;
    background: #ed691f;
    color: #ffffff;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-returned {
    border-radius: 4px;
    background: #d5d5d5;
    color: #000000;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-unqualified {
    border-radius: 4px;
    background: #101010;
    color: #ffffff;
    display: inline-block;
    padding: 0 5px;
  }
}
.order-history {
  :deep(.wd-cell) {
    background: none;
  }
}
</style>
